package com.phc.a20200511work.util;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.phc.a20200511work.interfaceBean.returndata;
import com.phc.a20200511work.javabean.webViedo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

/**
 * 版权：没有版权 看得上就用
 *
 * @author peng
 * 创建日期：2020/5/12 10
 * 描述：
 */
public class httpUtil extends AsyncTask<String , String , Boolean> {
    private static final String TAG = "httpUtil";
    
    Context context;
    returndata returndata_;
    private ProgressDialog progressDialog;
    private BufferedReader reader;


    public httpUtil(Context context, returndata returndata_) {
        this.context = context;
        this.returndata_ = returndata_;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //显示一个进度
        progressDialog = new ProgressDialog(context);
        progressDialog.setTitle("努力加载中~~~~~");
        progressDialog.setIndeterminate(true);
        progressDialog.show();
    }

    /**
     * 子线程任务
     * @param strings
     * @return
     */
    @Override
    protected Boolean doInBackground(String... strings) {
        try {
            URL url = new URL(strings[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            InputStream inputStream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line ;
            StringBuilder json = new StringBuilder();
            while ((line=reader.readLine()) != null ){
                json.append(line);
            }
            publishProgress(json.toString());
            //关闭流
            inputStream.close();
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        //接口回调将参数传递出去
        returndata_.back(values[0]);
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        progressDialog.cancel();
    }
}
